﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using Wulong.Phone.Dianping.Models;

namespace Wulong.Phone.Dianping.Services
{
    public class SearchService
    {
        public static IObservable<SearchSuggestion> ObservableSuggestion(
            string keywords, string cityCode, string channelId)
        {
            const string format = "http://www.dianping.com/search.v?q={0}&do=hs&c={1}&s={2}";
            var url = string.Format(format,
                                    keywords,
                                    cityCode,
                                    channelId
                                    );
            return SuggestionQuery(new Uri(url));
        }

        private static IObservable<SearchSuggestion> SuggestionQuery(Uri queryUrl)
        {
            return from request in Observable.Return((HttpWebRequest)WebRequest.Create(queryUrl)).Catch(Observable.Empty<HttpWebRequest>())
                   from response in Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)().Catch(Observable.Empty<WebResponse>())
                   from item in GetSuggestion(new StreamReader(response.GetResponseStream())).ToObservable().Catch(Observable.Empty<SearchSuggestion>())
                   .ObserveOn(Scheduler.ThreadPool)
                   select item;
        }

        private static IEnumerable<SearchSuggestion> GetSuggestion(StreamReader reader)
        {
            var strKeywords = reader.ReadToEnd();
            if (strKeywords.Length <= 30)
                return new[] {new SearchSuggestion()};
            strKeywords = strKeywords
                .Substring(27, strKeywords.Length - 30)
                .Replace("\"", "");
            return strKeywords
                .Split(',')
                .Select(item => item.Split('|'))
                .Select(arrSuggestion => 
                    new SearchSuggestion
                        {
                            Name = arrSuggestion[0],
                            Value = arrSuggestion[1],
                            ResultCount = arrSuggestion[2]
                        });
        }
    }
}
